﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.Mvc;
using System.Data;
using System.Configuration;

namespace JotCMS
{
    public static class JotContentHelper
    {
        public static string RenderJotEditControl(this HtmlHelper helper)
        {
            HttpContext.Current.Response.Write(@"<script type='text/javascript' language='javascript' src='/JotCMS/scripts/JotCMS.js'></script>");

            Jot.JotMode CurrentJotMode = GetCurrentJotMode();

            string editMsg = "Edit Page";
            if (CurrentJotMode == Jot.JotMode.Edit)
                editMsg = "Exit Edit Mode";

            string editControl = String.Format(@"<div style='border:1px solid black; padding: 5px; background-color: #FFFF99;position:absolute;top:0px;left:0px;'><img src='/JotCMS/images/edit.png' alt='{1}' /><a href='javascript:GoIntoEditMode({0});'>{1}</a></div>", (CurrentJotMode == Jot.JotMode.Edit ? 1 : 0), editMsg);

            return editControl;
        }

        public static string RenderJotContent(this HtmlHelper helper, string ContentName)
        {
            try
            {
                Jot jot = new Jot();
                jot.CurrentJotMode = GetCurrentJotMode();
                return CheckForEditMode(ContentName, jot.GetJotContent(ContentName).PublishedContent);
            }
            catch (Exception ex)
            {
                return String.Format("<span style='color:red'>Whoops, JotCMS had an issue: {0}</span>", ex.Message, ex.StackTrace);
            }
        }

        private static string CheckForEditMode(string ContentName, string content)
        {
            string editHandle = String.Format(@"<a href='javascript:OpenContentEdit(""{0}"")'><img src='/JotCMS/images/editContent.png' alt='click to Edit Content'></a>", ContentName);

            // if in edit mode
            if (GetCurrentJotMode() == Jot.JotMode.Edit)
                content += editHandle;

            return content;
        }

        private static Jot.JotMode GetCurrentJotMode()
        {
            Jot.JotMode mode = Jot.JotMode.Live;

            if (HttpContext.Current.Request.QueryString["JotEdit"] != null)
                mode = Jot.JotMode.Edit;

            return mode;
        }
    }
}